package com.zyh.flink.day06.assignor;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

public class SlidingWindowTest {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> hadoop10 = env.socketTextStream("hadoop10", 9999);
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = hadoop10.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] ss = s.split("\\s+");
                for (String s1 : ss) {
                    collector.collect(Tuple2.of(s1, 1));
                }
            }
        }).keyBy(t -> t.f0);
        /*
            通过滑动窗口进行无界数据流的切分
            窗口大小是5秒，滑动步长是3秒
         */
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = keyedStream
                .window(SlidingProcessingTimeWindows.of(Time.seconds(5), Time.seconds(3)))
                //基于windowedStream使用算子完成数据的处理: 对窗口内的数据进行处理
                .reduce(new ReduceFunction<Tuple2<String, Integer>>() {
                    @Override
                    public Tuple2<String, Integer> reduce(Tuple2<String, Integer> value1, Tuple2<String, Integer> value2) throws Exception {
                        return Tuple2.of(value1.f0, value1.f1 + value2.f1);
                    }
                });

        result.print();

        env.execute("Job");
    }
}
